/**
 *  帖子服务
 */
const { querySql, startTransaction, commitTransaction, rollbackTransaction } = require('../utils/index');
const boom = require('boom');
const { validationResult } = require('express-validator');
const {
  CODE_ERROR,
  CODE_SUCCESS
} = require('../utils/constant');
/* 提取公共的验证逻辑 */
function validateRequest(req, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
    return false;
  }
  return true;
}
/* 提取响应逻辑 */
function sendResponse(res, code, msg, data = null) {
  res.json({ code, msg, data });
}
/* 提取帖子查询逻辑 */
async function findPostById(id) {
  const query = `SELECT * FROM posts WHERE postId = ?`;
  return await querySql(query, [id]);
}
/* 创建帖子 */
async function createPost(req, res, next) {
  if (!validateRequest(req, next)) return;
  try {
    const { userId, title, content, image_url ,tags} = req.body;
    const sql = `INSERT INTO posts (title, content, userId, image_url,tags) VALUES (?, ?, ?, ?,?)`;
    const result = await querySql(sql, [title, content, userId, image_url,tags]);
    if (result.affectedRows === 1) {
      sendResponse(res, CODE_SUCCESS, '创建帖子成功', { postId: result.insertId });
    } else {
      sendResponse(res, CODE_ERROR, '创建帖子失败');
    }
  } catch (error) {
    next(boom.badImplementation(error.message));
  }
}
/* 获取帖子列表（带分页、排序和点赞状态）*/
async function getPostList(req, res, next) {
  try {
    const { 
      page = 1, 
      pageSize = 10, 
      sortBy = 'created_at', 
      order = 'DESC',
      userId,
      search = '', // 搜索内容
      tag = ''    // 新增：根据标签搜索
    } = req.query;

    // 参数验证（修改分页计算逻辑）
    const pageNumber = Math.max(1, parseInt(page));
    const size = pageSize * pageNumber; // 计算需要获取的累计数量
    const offset = 0; // 始终从0开始获取

    // 构建搜索条件
    let searchCondition = '';
    let searchParams = [];
    if (search) {
      searchCondition += 'p.content LIKE ?';
      searchParams.push(`%${search}%`);
    }
    if (tag) {
      if (searchCondition) searchCondition += ' AND ';
      searchCondition += 'p.tags LIKE ?';
      searchParams.push(`%${tag}%`);
    }

    // 优化后的SQL查询
    const sql = `
      SELECT 
        p.*,
        u.username,
        u.avatar_url,
        COUNT(DISTINCT c.commentId) AS comment_count,
        ${userId ? 
          `MAX(CASE WHEN l.userId = ? THEN 1 ELSE 0 END)` 
          : '0'} AS is_liked
      FROM posts p
      JOIN users u ON p.userId = u.id
      LEFT JOIN comments c ON p.postId = c.postId
      ${userId ? 'LEFT JOIN likes l ON p.postId = l.postId' : ''}
      ${searchCondition ? 'WHERE ' + searchCondition : ''}
      GROUP BY p.postId
      ORDER BY ${sortBy} ${order}
      LIMIT ? OFFSET ? 
    `;

    // 查询参数调整
    const params = [];
    if (userId) params.push(userId);
    params.push(...searchParams); // 添加搜索参数
    params.push(size, offset);

    // 执行查询
    const result = await querySql(sql, params);

    sendResponse(res, CODE_SUCCESS, '获取成功', {
      data: result.map(post => ({
        ...post,
        comment_count: Number(post.comment_count) || 0,
        is_liked: Boolean(post.is_liked),
        author: post.username || '未知用户'
      })),
      pagination: {
        currentPage: pageNumber,
        pageSize: pageSize, // 保持原始分页大小
        // 判断是否有更多数据：当实际获取数量等于请求数量时可能有更多数据
        hasMore: result.length === size 
      }
    });
  } catch (error) {
    next(boom.badImplementation(error.message));
  }
}
/* 获取帖子详情 */
async function getPostDetail(req, res, next) {
  try {
    const { postId } = req.query;
    
    // 查询帖子基础信息
    const postSql = `
      SELECT p.*, 
        u.username AS author_name,
        u.avatar_url AS author_avatar
      FROM posts p
      JOIN users u ON p.userId = u.id
      WHERE p.postId = ?
    `;
    const [post] = await querySql(postSql, [postId]);

    if (!post) {
      return sendResponse(res, CODE_ERROR, '帖子不存在');
    }

    // 查询全部评论
    const commentSql = `
      SELECT c.*, 
        u.username AS comment_author,
        u.avatar_url AS comment_avatar
      FROM comments c
      JOIN users u ON c.userId = u.id
      WHERE c.postId = ?
      ORDER BY c.created_at DESC
    `;
    const comments = await querySql(commentSql, [postId]);

    sendResponse(res, CODE_SUCCESS, '获取成功', {
      ...post,
      comments: comments.map(comment => ({
        id: comment.commentId,
        content: comment.content,
        createdAt: comment.created_at,
        author: {
          username: comment.comment_author,
          avatar: comment.comment_avatar
        }
      }))
    });
  } catch (error) {
    next(boom.badImplementation(error.message));
  }
}
/* 更新帖子 */
async function updatePost(req, res, next) {
  if (!validateRequest(req, next)) return;
  try {
    const { postId, title, content, image_url } = req.body;
    const sql = `UPDATE posts SET title = ?, content = ?, image_url = ? WHERE postId = ?`;
    const result = await querySql(sql, [title, content, image_url, postId]);
    if (result.affectedRows === 1) {
      sendResponse(res, CODE_SUCCESS, '更新帖子成功');
    } else {
      sendResponse(res, CODE_ERROR, '更新帖子失败');
    }
  } catch (error) {
    next(boom.badImplementation(error.message));
  }
}
/* 删除帖子 */
async function deletePost(req, res, next) {
  try {
    const { postId } = req.params;
    const sql = `DELETE FROM posts WHERE postId = ?`;
    const result = await querySql(sql, [postId]);
    if (result.affectedRows === 1) {
      sendResponse(res, CODE_SUCCESS, '删除帖子成功');
    } else {
      sendResponse(res, CODE_ERROR, '删除帖子失败');
    }
  } catch (error) {
    next(boom.badImplementation(error.message));
  }
}
/* 点赞帖子 */
async function likePost(req, res, next) {
  try {
    const { userId, postId } = req.body;
    let connection = null;
    try {
      // 开启事务
      connection = await startTransaction();
      // 检查是否已点赞
      const existingLike = await querySql(
        `SELECT likeId FROM likes WHERE userId = ? AND postId = ?`,
        [userId, postId],
        connection // 传递事务连接
      );
      if (existingLike && existingLike.length > 0) {
        await rollbackTransaction(connection);
        return sendResponse(res, CODE_ERROR, '已经点赞过啦');
      }
      // 插入点赞记录
      const insertResult = await querySql(
        `INSERT INTO likes (userId, postId) VALUES (?, ?)`,
        [userId, postId],
        connection
      );
      // 更新帖子点赞数
      await querySql(
        `UPDATE posts SET likes_count = likes_count + 1 WHERE postId = ?`,
        [postId],
        connection
      );
      // 提交事务
      await commitTransaction(connection);
      sendResponse(res, CODE_SUCCESS, '点赞成功');
    } catch (error) {
      if (connection) {
        await rollbackTransaction(connection);
      }
      next(boom.badImplementation(error.message));
    }
  } catch (error) {
    next(boom.badImplementation(error.message));
  }
}
/* 取消点赞 */
async function unlikePost(req, res, next) {
  try {
    const { userId, postId } = req.body;
    let connection = null;

    try {
      connection = await startTransaction();
      
      // 删除点赞记录
      const deleteResult = await querySql(
        `DELETE FROM likes WHERE userId = ? AND postId = ?`,
        [userId, postId],
        connection
      );

      if (deleteResult.affectedRows === 0) {
        await rollbackTransaction(connection);
        return sendResponse(res, CODE_ERROR, '未找到点赞记录');
      }

      // 更新帖子点赞数
      await querySql(
        `UPDATE posts SET like_counts = likes_count - 1 WHERE postId = ?`,
        [postId],
        connection
      );

      await commitTransaction(connection);
      sendResponse(res, CODE_SUCCESS, '取消点赞成功');
    } catch (error) {
      if (connection) {
        await rollbackTransaction(connection);
      }
      next(boom.badImplementation(error.message));
    }
  } catch (error) {
    next(boom.badImplementation(error.message));
  }
}
/* 获取用户帖子列表 */
async function getUserPostList(req, res, next) {
  try {
    const { userId, page = 1, pageSize = 10 } = req.query;
    const totalSize = page * pageSize; // 计算需要获取的累计数量
    const offset = 0; // 始终从0开始获取

    // 查询帖子列表
    const sql = `
      SELECT 
        p.*,
        u.username,
        u.avatar_url,
        COUNT(DISTINCT c.commentId) AS comment_count,
        0 AS is_liked
      FROM posts p
      JOIN users u ON p.userId = u.id
      LEFT JOIN comments c ON p.postId = c.postId
      WHERE p.userId = ?
      GROUP BY p.postId
      ORDER BY p.created_at DESC
      LIMIT ?, ?
    `;
    const result = await querySql(sql, [userId, offset, totalSize]);

    // 查询总条数
    const countSql = `SELECT COUNT(*) AS total FROM posts WHERE userId = ?`;
    const countResult = await querySql(countSql, [userId]);
    const total = countResult[0].total;

    // 返回格式与获取所有文章列表一致
    sendResponse(res, CODE_SUCCESS, '获取用户帖子列表成功', {
      data: result.map(post => ({
        ...post,
        comment_count: Number(post.comment_count) || 0,
        is_liked: Boolean(post.is_liked),
        author: post.username || '未知用户'
      })),
      pagination: {
        currentPage: parseInt(page),
        pageSize: parseInt(pageSize),
        total: total,
        hasMore: result.length < total
      }
    });
  } catch (error) {
    next(boom.badImplementation(error.message));
  }
}
/* 发布评论 */
async function commentPost(req, res, next) {
  if (!validateRequest(req, next)) return;
  try {
    const { userId, postId, content } = req.body;
    
    // 直接插入评论（移除事务和计数器更新）
    const insertSql = `INSERT INTO comments (postId, userId, content) VALUES (?, ?, ?)`;
    const result = await querySql(insertSql, [postId, userId, content]);

    if (result.affectedRows === 1) {
      sendResponse(res, CODE_SUCCESS, '评论成功', { 
        commentId: result.insertId 
      });
    } else {
      sendResponse(res, CODE_ERROR, '评论失败');
    }
  } catch (error) {
    next(boom.badImplementation(error.message));
  }
}
/* 获取所有评论 */
async function getCommentList(req, res, next) {
  try {
    const { 
      currentPage = 1, 
      pageSize = 10, 
      search = '' // 搜索内容
    } = req.body;

    // 确保 currentPage 和 pageSize 是数字
    const page = parseInt(currentPage, 10);
    const size = parseInt(pageSize, 10);
    const offset = (page - 1) * size;

    // 构建搜索条件
    let searchCondition = '';
    let searchParams = [];
    if (search) {
      searchCondition = 'WHERE c.content LIKE ?';
      searchParams.push(`%${search}%`);
    }

    // 查询评论列表
    const sql = `
      SELECT 
        c.*,
        u.username AS author,
        u.avatar_url AS author_avatar
      FROM comments c
      JOIN users u ON c.userId = u.id
      ${searchCondition}
      ORDER BY c.created_at DESC
      LIMIT ? OFFSET ?
    `;
    const result = await querySql(sql, [...searchParams, size, offset]);

    // 查询总条数
    const countSql = `
      SELECT COUNT(*) AS total 
      FROM comments c
      ${searchCondition}
    `;
    const countResult = await querySql(countSql, searchParams);
    const total = countResult[0].total;

    // 返回结果
    sendResponse(res, CODE_SUCCESS, '获取评论列表成功', {
      data: result,
      pagination: {
        currentPage: page,
        pageSize: size,
        total: total,
        hasMore: offset + size < total // 判断是否有更多数据
      }
    });
  } catch (error) {
    next(boom.badImplementation(error.message));
  }
}
/* 删除评论 */
async function deleteComment(req, res, next) {
  try {
    const { commentId } = req.body;

    // 检查评论是否存在
    const checkSql = `SELECT commentId FROM comments WHERE commentId = ?`;
    const [comment] = await querySql(checkSql, [commentId]);

    if (!comment) {
      return sendResponse(res, CODE_ERROR, '评论不存在');
    }

    // 删除评论
    const deleteSql = `DELETE FROM comments WHERE commentId = ?`;
    const result = await querySql(deleteSql, [commentId]);

    if (result.affectedRows === 1) {
      sendResponse(res, CODE_SUCCESS, '评论删除成功');
    } else {
      sendResponse(res, CODE_ERROR, '评论删除失败');
    }
  } catch (error) {
    next(boom.badImplementation(error.message));
  }
}
/* 获取所有点赞记录 */
async function getAllLikes(req, res, next) {
  try {
    const { 
      currentPage = 1, 
      pageSize = 10, 
      search = '' // 搜索内容（可选）
    } = req.body;

    // 确保 currentPage 和 pageSize 是数字
    const page = parseInt(currentPage, 10);
    const size = parseInt(pageSize, 10);
    const offset = (page - 1) * size;

    // 构建搜索条件
    let searchCondition = '';
    let searchParams = [];
    if (search) {
      searchCondition = 'WHERE u.username LIKE ? OR p.title LIKE ?';
      searchParams.push(`%${search}%`, `%${search}%`);
    }

    // 查询点赞记录
    const sql = `
      SELECT 
        l.*,
        u.username AS user_name,
        p.title AS post_title
      FROM likes l
      JOIN users u ON l.userId = u.id
      JOIN posts p ON l.postId = p.postId
      ${searchCondition}
      ORDER BY l.created_at DESC
      LIMIT ? OFFSET ?
    `;
    const result = await querySql(sql, [...searchParams, size, offset]);

    // 查询总条数
    const countSql = `
      SELECT COUNT(*) AS total 
      FROM likes l
      JOIN users u ON l.userId = u.id
      JOIN posts p ON l.postId = p.postId
      ${searchCondition}
    `;
    const countResult = await querySql(countSql, searchParams);
    const total = countResult[0].total;

    // 返回结果
    sendResponse(res, CODE_SUCCESS, '获取点赞记录成功', {
      data: result,
      pagination: {
        currentPage: page,
        pageSize: size,
        total: total,
        hasMore: offset + size < total // 判断是否有更多数据
      }
    });
  } catch (error) {
    next(boom.badImplementation(error.message));
  }
}
module.exports = {
  createPost,
  getPostList,
  getPostDetail,
  updatePost,
  deletePost,
  getUserPostList,
  likePost,
  commentPost,
  getCommentList,
  deleteComment,
  getAllLikes
};